import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { AllotmentService } from './allotment.service';
import { FileUploadNormalComponent } from '../purchase/file-upload-normal/file-upload-normal.component';
import { AppPaginationComponent, PaginationModel } from '../../../widgets/pagination/pagination.component';
import { Util } from "../../../common/util";
import { environment } from '../../../../environments/environment';
import * as moment from 'moment';
import * as _ from 'lodash';

@Component({
  selector: 'new-stock-allotment',
  templateUrl: './allotment.component.html',
  styleUrls: ['./allotment.component.scss'],
  providers: [AllotmentService]
})
export class AllotmentComponent implements OnInit {

  public $ = window["$"];

  // 列表当前页全选标记
  public isCheckedAll = false;

  // 配售对象数据列表
  public allotmentObjList: Array<any>;

  // 基金或万德模态框配置
  public modalOpt: any = {
    fundOrWind: ''
  };

  // 配售对象
  public allotmentObj = {
    vcRationCode: "", // 配售对象编码
    vcRationName: "", // 配售对象名称
    vcFundCode: "", // 所属基金
    vcXiehuiCode: "", // 协会编码
    windOrgCode: "", // 万德机构编码
    windOrgName: "" // 万德机构名称
  };

  // 查询条件
  public searchBody = {
    vcRationCode: "", // 按配售对象名称模糊查询
    vcRationName: "", // 按配售对象查询
    vcFundCode: "", // 按所属基金查询
    vcDateState: "",
    page: 1, // 页码
    pageSize: environment.pageSize
  };

  // 模态框基金查询条件
  public modalFundSearch: any = {
    vcFundCode: '',
    vcFundName: ''
  };

  // 模态框万德查询条件
  public modalWindSearch: any = {
    windOrgCode: '',
    windOrgName: ''
  };

  // 模态框接收数据
  public modalData: any = [];


  // 模态框选中数据
  public modalCheckedData: any = {
    fund: {},
    Wind: {}
  };

  // 分页数据模型
  public pageInfo: PaginationModel = {
    currentPageNum: 1,
    pageSize: 10,
    totalPages: 1,
    total: 0,
    pagesShow: 5,
    startRow: 0,
    endRow: 0,
    pageList: [5, 10, 25, 50, 100]
  };

  // 标记新增或更新：1 表示新增  0 表示更新
  public isAdd = 1;

  constructor(public allotmentService: AllotmentService) {
    this.getAllotmentObjList();
  }

  ngOnInit() {
  }

  /**
   * [checkedAll 列表当前页全选]
   */
  checkedAll() {
    if (this.isCheckedAll) { // 更新为全选
      _.forEach(this.allotmentObjList, item => {
        item.isChecked = true;
      });
    } else { // 更新为不全选
      _.forEach(this.allotmentObjList, item => {
        item.isChecked = false;
      });
    }
  }

  /**
   * [checked 是否需要更新全选]
   * @param {[type]} remittance [实例对象]
   */
  checked(remittance) {
    if (remittance.isChecked) {
      const temp = _.find(this.allotmentObjList, { isChecked: false });
      if (!temp) { // 全选重置为 true
        this.isCheckedAll = true;
      }
    } else { // 全选重置为 false
      this.isCheckedAll = false;
    }
  }

  /**
   * [reflesh 刷新列表]
   * @param {[type]} event [description]
   */
  reflesh(event?) {

  }

  /**
   * [search 查询]
   */
  search() {
    this.getAllotmentObjList();
  }

  resetSearch() {
    this.searchBody = {
      vcRationCode: "", // 按配售对象名称模糊查询
      vcRationName: "", // 按配售对象查询
      vcFundCode: "", // 按所属基金查询
      vcDateState: "",
      page: 1, // 页码
      pageSize: this.pageInfo.pageSize
    };
  }

  /**
   * [openModal 打开modal]
   * @param {[type]} type         [1-新增，0-修改]
   * @param {[type]} allotmentObj [description]
   */
  public openModal(type, allotmentObj?) {
    if (type === 0) { // 更新
      this.isAdd = 0; // 修改标记
      // 初始化更新表单页面
      this.allotmentObj.vcFundCode = allotmentObj.vcFundCode;
      this.allotmentObj.vcRationCode = allotmentObj.vcRationCode;
      this.allotmentObj.vcRationName = allotmentObj.vcRationName;
      this.allotmentObj.vcXiehuiCode = allotmentObj.vcXiehuiCode;
      this.allotmentObj.windOrgCode = allotmentObj.windOrgCode;
      this.allotmentObj.windOrgName = allotmentObj.windOrgName;
    } else {
      this.isAdd = 1; // 修改标记
    }

    Util.$("#allotmentModal").modal("show");
  }

  /**
   * [closeModal 关闭modal]
   */
  public closeModal() {
    Util.$("#allotmentModal").modal("hide");

    // 重置为空
    this.allotmentObj = {
      vcRationCode: "",
      vcRationName: "",
      vcFundCode: "",
      vcXiehuiCode: "",
      windOrgCode: "",
      windOrgName: ""
    };
  }

  /**
   * [closeModal 关闭modal]
   */
  public closeFundOrWindModal() {
    Util.$("#fundOrWindModal").modal("hide");

    this.resetFundOrWindModal();
  }

  /**
   * [getAllotmentObjList 获取列表]
   */
  getAllotmentObjList() {
    // 设置查询条件页码
    this.searchBody.page = this.pageInfo.currentPageNum;
    this.searchBody.pageSize = this.pageInfo.pageSize;

    this.allotmentService.getAllotmentObjList(this.searchBody).subscribe(data => {
      if (data) {
        this.allotmentObjList = data.list;
        // 构建分页
        this.pageInfo.totalPages = data.pages;
				this.pageInfo.total = data.total;
				this.pageInfo.startRow = data.startRow;
				this.pageInfo.endRow = data.endRow;
        this.allotmentObjList.forEach(item => {
          item.isChecked = false
        });
      }
    });
  }

  // 批量复核
  public checkRation() {
    var that = this;
    var checkedData = _.filter(this.allotmentObjList, { isChecked: true });
    var answer = that.validateRation(checkedData);
    if (answer.isPass === false) {
      return window["swal"]("提示", answer.message, "info");
    } else {
      window["swal"]({
        title: "提示",
        text: "是否确定复核?",
        type: "info",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        closeOnConfirm: false,
        closeOnCancel: true,
        showLoaderOnConfirm: true
      },
        function (isConfirm) {
          if (isConfirm) { // 确认
            that.allotmentService.checkRation(answer.RationCodeArr).subscribe(result => {
              if (result) {
                if (result.code === 0) {
                  that.search();
                  return window["swal"]("提示", "复核成功", "info");
                }
              }
            })
          }
        });
    }
  }

  // 校验是否有复核资格并且取出配售代码进行请求
  public validateRation(data) {
    var answer: any = {
      isPass: false,
      message: "",
      RationCodeArr: []
    };
    if (data.length === 0) {
      answer.message = "请选择一条数据进行操作";
      return answer;
    } else {
      data.forEach(item => {
        if (item.vcDateState !== "0") {
          answer.message = "非待复核数据不能进行复核操作！";
        } else {
          answer.RationCodeArr.push(item.vcRationCode);
        }
      })
    }
    if (answer.message === "") {
      answer.isPass = true;
      answer.RationCodeArr = answer.RationCodeArr.join(",");
    }
    return answer;
  }


  // 校验配售对象模态框
  validateAllotmentModal() {
    var isPass = true;
    var $ = window["$"];
    var that = this;
    $(".allotmentModal-input").each((index, item) => {
      if (item.value === "") {
        window["swal"]("提示", item.placeholder + "不能为空", "info");
        isPass = false;
        return false;
      }
    });
    return isPass;
  }

  /**
   * [addOrUpdateAllotmentObj 新增配售对象]
   */
  addAllotmentObj() {
    const that = this;
    if (that.validateAllotmentModal()) {
      window["swal"]({
        title: "提示",
        text: "是否确定要新增配售对象?",
        type: "info",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        closeOnConfirm: false,
        closeOnCancel: true,
        showLoaderOnConfirm: true
      },
        function (isConfirm) {
          if (isConfirm) { // 确认
            that.allotmentService.addAllotmentObj(that.allotmentObj).subscribe(data => {
              if (data) {
                window["swal"]("新增成功", "", "success");
                that.getAllotmentObjList(); // 重新加载列表数据
                that.closeModal();
              }
            });
          }
        });
    }
  }

  /**
   * [updateAllotmentObj 更新配售对象]
   */
  updateAllotmentObj() {
    const that = this;
    window["swal"]({
      title: "提示",
      text: "是否确定要更新配售对象?",
      type: "info",
      showCancelButton: true,
      confirmButtonColor: "#DD6B55",
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      closeOnConfirm: false,
      closeOnCancel: true,
      showLoaderOnConfirm: true
    },
      function (isConfirm) {
        if (isConfirm) { // 确认
          console.log("更新配售对象信息：" + JSON.stringify(that.allotmentObj));
          that.allotmentService.addAllotmentObj(that.allotmentObj).subscribe(data => {
            if (data) {
              window["swal"]("更新成功", "", "success");
              // 重置为空
              that.allotmentObj = {
                vcRationCode: "",
                vcRationName: "",
                vcFundCode: "",
                vcXiehuiCode: "",
                windOrgCode: "",
                windOrgName: ""
              };
              // 重新加载列表数据
              that.getAllotmentObjList();
              that.closeModal();
            }
          });
        } else { // 取消
          // window["swal"]("Cancelled", "Your imaginary file is safe :)", "error");
        }
      });
  }

  /**
   * [deleteAllotmentObj 删除配置对象]
   */
  deleteAllotmentObj(item) {
    const that = this;
    window["swal"]({
      title: "提示",
      text: "是否确定要删除配售对象?",
      type: "info",
      showCancelButton: true,
      confirmButtonColor: "#DD6B55",
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      closeOnConfirm: false,
      closeOnCancel: true,
      showLoaderOnConfirm: true
    },
      function (isConfirm) {
        if (isConfirm) { // 确认
          that.allotmentService.deleteAllotmentObj(item).subscribe(data => {
            if (data) {
              window["swal"]("更新成功", "", "success");
              // 刷新列表
              that.getAllotmentObjList();
            }
          });
        } else { // 取消
          // window["swal"]("Cancelled", "Your imaginary file is safe :)", "error");
        }
      });
  }

  // 打开二级模态框（基金选择）并查询
  public openFundOrWindModal(item, type) {
    this.modalOpt.fundOrWind = type;
    this.$("#fundOrWindModal").modal('show');
    this.fundOrWindModalSearch();
  }

  // 基金或万德模态框搜索
  public fundOrWindModalSearch() {
    const param: any = {
      page: 1,
      pageSize: 100
    };
    if (this.modalOpt.fundOrWind === "fund") {
      param.vcFundCode = this.modalFundSearch.vcFundCode;
      param.vcFundName = this.modalFundSearch.vcFundName;
      return this.allotmentService.getFundInfo(param).subscribe(result => {
        if (result) {
          this.modalData = result.data;
        }
      });
    }
    if (this.modalOpt.fundOrWind === "Wind") {
      param.windOrgCode = this.modalWindSearch.windOrgCode;
      param.windOrgName = this.modalWindSearch.windOrgName;
      return this.allotmentService.getWindInfo(param).subscribe(result => {
        if (result) {
          this.modalData = result.data.list;
        }
      });
    }
  }

  // 基金或万德选中函数
  public fundModalChecked(item, $event) {
    if ($event.target.checked) {
      if (this.modalOpt.fundOrWind === "fund") {
        this.modalCheckedData.fund.vcFundCode = item.vcFundCode;
        this.modalCheckedData.fund.vcFundName = item.vcFundName;
      }
      if (this.modalOpt.fundOrWind === "Wind") {
        this.modalCheckedData.Wind.windOrgCode = item.windOrgCode;
        this.modalCheckedData.Wind.windOrgName = item.windOrgName;
      }
    }
  }

  public confirmModalData() {
    this.allotmentObj.vcFundCode = this.modalCheckedData.fund.vcFundCode;
    this.allotmentObj.windOrgCode = this.modalCheckedData.Wind.windOrgCode;
    this.allotmentObj.windOrgName = this.modalCheckedData.Wind.windOrgName;
    this.$("#chooseFundModal").modal('hide');
    this.resetFundOrWindModal();
  }

  // 初始化基金或万德模态框
  public resetFundOrWindModal() {
    this.modalFundSearch.vcFundCode = "";
    this.modalFundSearch.vcFundName = "";
    this.modalWindSearch.windOrgCode = "";
    this.modalWindSearch.windOrgName = "";
    this.modalData = [];
  }

  /**
   * 根据页码请求查询相关配置列表数据,如果当前活动页码就是目标页码，则不进行任何查询
   * 直接返回
   * @param {currentPageNum}
   */
  public pageNavigation(currentPageNum: number) {
    this.pageInfo.currentPageNum = currentPageNum;
    this.search();
  }

  /**
   * 改变每页显示记录数
   * @param {pageSize}
   */
  public pageSizeChange(pageSize: number) {
    if (pageSize !== this.pageInfo.pageSize) {
      this.pageInfo.pageSize = pageSize;
      this.pageInfo.currentPageNum = 1;
      this.search();
    }
  }


}
